<template>
  <div class="we-chat-public-channel views-container">
    <!-- 弹窗二维码 -->
    <el-dialog
      :visible.sync="dialogVisibleImg"
      width="33%"
      custom-class="reset-pwd wlm-form-dialog dialog-table"
      :before-close="binimgColse"
    >
      <div class="wlm-form">
        <div class="wlm-form-header wlm-dialog-fixheader">
          <span class="wlm-dialog-inlenr">页面推广</span>
        </div>
        <div
          class="flex-col flex-align-c flex-justify-c"
          style="margin:20px 0"
          v-loading="bindQrcodeImgLoading"
        >
          <img height="220" width="220" style="margin:10px 0 30px" :src="bindQrcodeImg" alt />
          <!-- <div class="flex-col"> -->
          <p style="margin-bottom:20px">微信扫一扫绑定用户</p>
          <!-- </div> -->
        </div>
      </div>
    </el-dialog>

    <div class="wlm-table">
      <!-- 顶部样式 -->
      <div class="warning">
        <div class="flex-row flex-justify-b flex-align-c">
          <div>
            <p class="warning-title">微信公众号</p>
            <p style="margin-top:10px;">绑定微信公众号，系统将接入微信公众号，平台用户可以通过绑定公众号用户进行扫码登录</p>
          </div>
          <div>
            <el-button
              style="margin-right:20px;"
              size="small"
              plain
              class="orders-blue"
              @click="showForm"
              v-if="formData.app_id && !isShowForm"
            >修改配置</el-button>
          </div>
        </div>
      </div>

      <!-- 编辑公众号设置表单 -->
      <div class="flex-row flex-warp form-group" v-if="!notShowData">
        <div class="wlm-form">
          <section>
            <div class="wlm-form-content channel-card">
              <el-form
                :model="formData"
                size="small"
                label-width="230px"
                class="retail-form"
                label-position="right"
              >
                <div v-if="!isOpenEdit">
                  <div class="wlm-form-header flex-row" style="margin-bottom:20px;">
                    微信绑定
                    <p style="margin-left:8px;" class="form-help">总管理员账号与微信号绑定</p>
                  </div>

                  <!-- 绑定微信账号信息 -->
                  <div v-if="adminWechatData.length > 0" style="display:flex;flex-wrap:wrap;">
                    <div v-for="(item,index) in adminWechatData" :key="index" style="margin: 0 0 50px 0;">
                      <el-form-item label="绑定微信头像" prop="repassword" class="slider">
                        <img
                          class="wlm-upload-img"
                          :src="item.headimgurl"
                          style="border-radius: 50%;"
                        />
                      </el-form-item>
                      <el-form-item label="绑定微信昵称" prop="password">
                        <span>{{item.nickname}}</span>
                      </el-form-item>
                      <el-form-item label="绑定OPEN_ID" prop="password">
                        <span>{{item.open_id}}</span>
                      </el-form-item>
                      <el-form-item label prop="password">
                        <el-button plain @click="unBind(item.open_id)">取消绑定</el-button>
                      </el-form-item>
                    </div>
                  </div>
                  <div>
                    <el-form-item label prop="password">
                      <el-button
                        @click="bindWechat"
                        class="status-main-btn"
                        type="success"
                        style="background:rgb(104, 211, 135);border:none;"
                      >
                        <i class="el-icon-link" style="font-size:16px;font-weight:bold;"></i>&nbsp; 绑定微信账号
                      </el-button>
                    </el-form-item>
                  </div>
                </div>

                <div class="wlm-form-header flex-row" style="margin-bottom:20px;">
                  公众号
                  <p style="margin-left:8px;" class="form-help">公众号基础配置</p>
                </div>
                <el-form-item label="应用模式" prop="password">
                  <el-radio v-model="formData.oauth" label="1" :disabled="!isOpenEdit">关注公众号授权</el-radio>
                  <el-radio v-model="formData.oauth" label="2" :disabled="!isOpenEdit">网页授权</el-radio>
                </el-form-item>
                <el-form-item label="app_id" prop="password">
                  <span v-if="!isOpenEdit">{{formData.app_id}}</span>
                  <el-input v-if="isOpenEdit" v-model="formData.app_id"></el-input>
                </el-form-item>
                <el-form-item label="AppSecret" prop="repassword">
                  <span v-if="!isOpenEdit">{{formData.secret}}</span>
                  <el-input v-if="isOpenEdit" v-model="formData.secret"></el-input>
                </el-form-item>
                <div v-if="formData.oauth == 1">
                  <el-form-item label="二维码" prop="repassword" class="slider">
                  <img
                    v-if="!isOpenEdit"
                    class="wlm-upload-img"
                    :src="formData.img  ? formData.img['file_path'] : `${require('@/assets/custorm_style/default_picture.png')}`"
                  />
                  <choose-files
                    v-if="isOpenEdit"
                    ref="chooseFiles"
                    :config="chooseBgConfig"
                    :changeEvt="formFormatFiltersChange"
                  ></choose-files>
                </el-form-item>
                  <div class="wlm-form-header flex-row" style="margin-bottom:20px;">
                    消息推送
                    <p style="margin-left:8px;" class="form-help">公众号服务器配置</p>
                  </div>

                  <el-form-item label="URL(服务器地址)">
                    <span
                      style="margin-left:0;"
                      class="pointer"
                      @click="handleClipboard(formData.url,$event)"
                    >{{formData.url}}</span>
                    <p class="form-help">点击复制链接</p>
                    <!-- <span v-if="formFormatData.formData.channel.wechat.authorized" >{{formFormatData.formData.channel.wechat.authorized.url.replace(/amp;/g,'')}}</span> -->
                  </el-form-item>
                  <el-form-item label="Token(令牌)">
                    <span
                      style="margin-left:0;"
                      class="pointer"
                      v-if="!isOpenEdit"
                      @click="handleClipboard(formData.token,$event)"
                    >{{formData.token}}</span>
                    <p class="form-help" v-if="!isOpenEdit">点击复制链接</p>
                    <div v-if="isOpenEdit" class="flex-row">
                      <el-input maxlength="32" v-if="isOpenEdit" v-model="formData.token"></el-input>
                      <el-button
                        style="margin-left:10px;"
                        type="text"
                        @click="setRandom(32,'token')"
                      >随机生成</el-button>
                    </div>
                  </el-form-item>
                  <el-form-item label="EncodingAESKey(消息加密密钥)">
                    <span
                      style="margin-left:0;"
                      class="pointer"
                      v-if="!isOpenEdit"
                      @click="handleClipboard(formData.EncodingAESKey,$event)"
                    >{{formData.EncodingAESKey}}</span>
                    <p class="form-help" v-if="!isOpenEdit">点击复制链接</p>
                    <div v-if="isOpenEdit" class="flex-row">
                      <el-input maxlength="43" v-if="isOpenEdit" v-model="formData.EncodingAESKey"></el-input>
                      <el-button
                        style="margin-left:10px;"
                        type="text"
                        @click="setRandom(43,'EncodingAESKey')"
                      >随机生成</el-button>
                    </div>
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </section>
        </div>
      </div>

      <!-- 没有配置时显示立即接入样式 -->
      <div class="wlm-form" v-if="!formData.app_id && !isShowForm">
        <section>
          <div class="wlm-form-content channel-card">
            <div class="status-main pos-center">
              <div class="flex-row flex-justify-c">
                <div class="flex-col">
                  <el-button
                    @click="showForm"
                    class="status-main-btn"
                    type="success"
                    style="background:rgb(104, 211, 135);border:none;"
                  >
                    <i>
                      <svg-icon class="status-main-svg" icon-class="wechat" />
                    </i>&nbsp; 立即接入
                  </el-button>
                  <div class="flex-row flex-justify-e mar-top-4">
                    <div>
                      没有公众号，去
                      <a
                        target="_blank"
                        href="https://mp.weixin.qq.com/"
                        class="alink-blue"
                      >注册</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>

    <!-- 保存 -->
    <div v-if="isOpenEdit" v-cloak class="wlm-fixed-btn flex-row flex-align-c flex-justify-c">
      <el-button size="small" @click="saveForm" type="primary">保存</el-button>
      <el-button @click="outForm" size="small">取消</el-button>
    </div>
  </div>
</template>

<script>
import {
  adminWechatGet,
  adminWechatSave,
  adminBindQrcode,
  adminBindResult,
  adminBindInfo,
  adminUnBind
} from '@/api/setting'
import clipboard from '@/utils/clipboard'
import ChooseFiles from '@/components/ChooseFiles/index'
export default {
  created() {
    this.dataGet()
  },
  components: {
    ChooseFiles
  },
  data() {
    return {
      bindQrcodeImg: '',
      dialogVisibleImg: false,
      bindQrcodeImgLoading: true,
      // 显示数据
      notShowData: true,
      // 是否显示表单
      isShowForm: false,
      // 是否可以编辑
      isOpenEdit: false,
      chooseBgConfig: {
        type: ['image'],
        model: 'display',
        uploadConfig: {
          limit: 1,
          isMore: true,
          model: 'display',
          initList: []
        },
        initList: [],
        isShowList: true,
        file_type: 'image',
        bindKey: {
          key: 'img',
          model: 'img'
          // validateField: 'businessbackgroundmap'
        },
        // 直接显示的文件数据
        showData: []
      },
      formData: {
        app_id: '',
        secret: '',
        token: '',
        img: [],
        url: '',
        oauth: '2',
        EncodingAESKey: ''
      },
      // 管理端绑定微信数据
      adminWechatData: {},
      unBindResult: false
    }
  },
  methods: {
    // 请求已设置数据
    dataGet() {
      // 基础设置数据
      adminWechatGet({ key: 'wechat' }).then((res) => {
        // 将获取到的数据挂载到暴露的data数据中
        this.formData = { ...res.data.data }
        // 回显图片
        this.chooseBgConfig.uploadConfig.initList[0] = this.formData.img
        // 如果app_id存在，证明接入小程序，显示数据
        if (this.formData.app_id) {
          this.notShowData = false
        }
      })
      // 管理员绑定数据
      this.adminBindInfo()
    },
    adminBindInfo() {
      adminBindInfo().then((res) => {
        if (res.data.code == 1) {
          this.adminWechatData = res.data.data
        }
      })
    },
    // 图片选择器回调
    formFormatFiltersChange(data) {
      if (data.displayData && data.displayData[0]) {
        this.formData.img = data.displayData[0]
      }
    },
    // 进入表单进行编辑
    showForm() {
      // 点击立即接入显示表单进行编辑
      this.isShowForm = true
      // 各项数据可以编辑
      this.isOpenEdit = true
      // 数据展示
      this.notShowData = false
    },
    // 退出表单编辑
    outForm() {
      this.dataGet()
      this.isOpenEdit = false
      this.isShowForm = false
      if (!this.formData.app_id) {
        this.notShowData = true
      }
    },
    // 提交保存
    saveForm() {
      adminWechatSave({ key: 'wechat', ...this.formData }).then((res) => {
        if (res.data.code == 1) {
          // 如果app_id不存在，证明未接入小程序，不显示数据
          if (!this.formData.app_id) {
            this.notShowData = true
          }
          this.$message.success('保存成功！')
          this.outForm()
        } else {
          this.$message.error('保存失败！')
        }
      })
    },
    // 复制
    handleClipboard(text, event) {
      clipboard(text, event)
    },
    // 随机生成字符串
    setRandom(len, name) {
      len = len || 32
      var $chars =
        'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      this.formData[`${name}`] = pwd
    },
    // 获取管理员绑定二维码
    bindWechat() {
      this.dialogVisibleImg = true
      adminBindQrcode().then((res) => {
        if (res.data.code == 1) {
          this.bindQrcodeImg = res.data.data
          this.bindQrcodeImgLoading = false
          this.unBindResult = true
          this.bindResult()
        }
      })
    },
    // 轮询获取绑定结果
    bindResult() {
      adminBindResult().then((res) => {
        if (this.unBindResult == false) {
          this.dialogVisibleImg = false
          this.bindQrcodeImgLoading = true
          return ''
        }
        if (res.data.code == 1 && res.data.data === false) {
          this.bindResult()
        } else if (res.data.data === true || res.data.code == 0) {
          this.$message.success('绑定成功~')
          this.dataGet()
          this.dialogVisibleImg = false
          this.bindQrcodeImgLoading = true
        }
      })
    },
    // 取消绑定
    unBind(open_id) {
      this.$confirm('此操作将会取消该管理员的微信绑定, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          adminUnBind({ open_id }).then((res) => {
            if (res.data.code == 1) {
              this.$message.success('取消绑定成功！')
              this.adminBindInfo()
            } else {
              this.$message.error('取消绑定失败！')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    binimgColse() {
      this.unBindResult = false
    }
  }
}
</script>

<style lang="scss" scoped>
.we-chat-public-channel {
  .form-group {
    .wlm-form {
      width: 500px;
      flex-grow: 1;
      margin-right: 20px;
    }
  }
}
</style>
